class Cart {
    constructor() {
        this.res()
        // 商品显示
        this.addCar()
        // 绑定点击事件
        this.bindEve()
        // 登录状态
        this.loginStatus()
    }
    // 添加响应拦截器
    res() {
        axios.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            if (response.data.code == 401) location.assign('./login.html')
            // console.log(response);
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }
    // 获取用户ID
    userId = localStorage.getItem('id');
    // 判断登录状态  将用户购物车数据渲染到页面中
    addCar() {
        let html = ""
        // 获取token
        let token = localStorage.getItem('token');
        //判断是否登录
        if (!token) location.assign('./login.html')
        // 发送请求
        axios.defaults.headers.common['Authorization'] = token;
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        let pra = `id=${this.userId}`
        axios.get('http://localhost:8888/cart/list?' + pra).then(({
            data,
            status
        }) => {
            // console.log(data, status);
            // 判断
            if (status != 200) return
            if (data.code != 1) location.assign('./login.html')
            // 将数据渲染到页面中
            data.cart.forEach(ele => {
                html += `<ul class="goods-list yui3-g" data-id="${ele.goods_id}">
            <li class="yui3-u-3-8 pr">
                <input type="checkbox" class="good-checkbox">
                <div class="good-item">
                    <div class="item-img">
                        <img src="${ele.img_small_logo}">
                    </div>
                    <div class="item-msg">${ele.title}</div>
                </div>
            </li>
            <li class="yui3-u-1-8">
            </li>
            <li class="yui3-u-1-8">
                <span class="price">${ele.current_price}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="clearfix">
                    <a href="javascript:;" class="increment mins">-</a>
                    <input autocomplete="off" type="text" value="${ele.cart_number}" minnum="1" class="itxt">
                    <a href="javascript:;" class="increment plus">+</a>
                </div>
                <div class="youhuo">有货</div>
            </li>
            <li class="yui3-u-1-8">
                <span class="sum">${(ele.current_price*ele.cart_number).toFixed(2)}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="del1">
                    <a href="javascript:;" class="del">删除</a>
                </div>
                <div>移到我的关注</div>
            </li>
        </ul>`
            });
            //追加到页面中
            this.$('.cart-list').innerHTML = html
        })
    }
    bindEve() {
        // 全选
        // console.log(this.$('.cart-th input'));
        this.$('.cart-th input').addEventListener('click', this.allSel.bind(this))
        // 事件委托
        this.$('.cart-list').addEventListener('click', this.goods.bind(this))
    }
    goods(eve) {
        // 获取事件源
        let tar = eve.target
        // console.log(tar);
        let ul = this.parent(tar);
        // console.log(ul);
        // 判断点击的是什么 
        // 单选
        if (tar.classList.contains('good-checkbox')) {
            this.oneSta(tar)
            this.mount()
        }
        // 删除
        if (tar.classList.contains('del')) {
            this.delete(tar)
        }
        // 加号与减号
        // 减号
        if (tar.classList.contains('increment')) {
            let val = ""
            if (tar.innerHTML == '-') {
                val = this.val(tar)
                val--
                if (val < 1) val = 1
                tar.nextElementSibling.value = val;
                this.change(tar, val)
            }
            // 加号
            if (tar.innerHTML == '+') {
                val = this.val(tar)
                val++
                tar.previousElementSibling.value = val;
                this.change(tar, val)
            }
            // 获取单价
            let price = ul.querySelector('.price').innerHTML;
            // console.log(price);
            // 设置小计
            ul.querySelector('.sum').innerHTML = (price * val).toFixed(2)
            this.mount()
        }
        if (tar.classList.contains('itxt')) {
            tar.addEventListener('blur', this.onblur.bind(this, tar, ul))
        }
    }
    // 输入事件
    onblur(tar, ul) {
        // console.log(ul);
        let val = this.val(tar)
        this.change(tar, val)
        // 获取单价
        let price = ul.querySelector('.price').innerHTML;
        // console.log(price);
        // 设置小计
        ul.querySelector('.sum').innerHTML = (price * val).toFixed(2)
        this.mount()
    }
    times = ""
    // 更改数量请求
    change(tar, val) {
        let that = this;
        // 防抖
        clearTimeout(this.times)
        this.times = setTimeout(function () {
            // console.log(this);//window
            // 获取token
            let token = localStorage.getItem('token');
            //判断是否登录
            if (!token) location.assign('./login.html');
            // 获取用户ID
            let userId = localStorage.getItem('id');
            // 获取商品id
            let goodsId = that.parent(tar).dataset.id;
            // 获取商品数量
            // let val = that.val(tar)
            // console.log(val);
            // console.log(goodsId);
            // 发送请求
            axios.defaults.headers.common['Authorization'] = token;
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            let par = `id=${userId}&goodsId=${goodsId}&number=${val}`
            axios.post('http://localhost:8888/cart/number', par).then(res => {
                // console.log(res);
            })
        }, 500)
    }
    // 获取value值
    val(tar) {
        // console.log(tar);
        // 获取父级节点
        let ul = this.parent(tar)
        // 获取指定的子节点
        let val = this.boy(ul, '.itxt', 'value')
        return val
    }
    // 删除的实现
    delete(tar) {
        // 设置this
        let that = this;
        //弹出框

        layer.msg('确认删除吗', {
            time: 10000, //不自动关闭
            btn: ['确定', '关闭'],
            yes: function (index) {
                layer.close(index);
                // 确认后要做的事情
                // 获取请求
                // 获取token
                let token = localStorage.getItem('token');
                // 获取用户ID
                let userId = localStorage.getItem('id');
                // console.log(this);
                // 获取商品id
                let ul = that.parent(tar);
                // console.log(ul, userId);
                //判断是否登录
                if (!token) location.assign('./login.html')
                // 发送请求
                axios.defaults.headers.common['Authorization'] = token;
                axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                let pra = `id=${userId}&goodsId=${ul.dataset.id}`
                axios.get('http://localhost:8888/cart/remove?' + pra).then(({
                    data,
                    status
                }) => {
                    // 判断
                    if (status != 200) return
                    if (data.code != 1) location.assign('./login.html')
                    // 删除父级节点 
                    ul.remove()
                    // 判断当前节点的input是否为选中 如果为选中 重新计算总价
                    that.boy(ul, '.good-checkbox', 'checked') && that.mount()
                })
            }
        });
    }
    // 数量与小计
    mount() {
        let sum1 = 0
        let num1 = 0
        // 获取父级节点集合
        let btn = document.querySelectorAll('.goods-list')
        // console.log(btn);
        btn.forEach(ele => {
            let status = this.boy(ele, '.good-checkbox', 'checked')
            // 判断状态
            if (status) {
                // 获取数量
                let num = (this.boy(ele, '.itxt', 'value') - 0);
                // console.log(num);
                // 获取小计
                let sum = (this.boy(ele, '.sum', 'innerHTML') - 0)
                // console.log(sum);
                num1 += num
                sum1 += sum
            }
        })
        // console.log(num1, sum1);
        // 将获取数据设置到页面中
        this.$('.sumprice-top strong').innerHTML = num1
        this.$('.summoney span').innerHTML = sum1.toFixed(2)
    }
    // 全选
    allSel() {
        // 获取全选按钮状态
        let status = this.$('.cart-th input').checked
        // console.log(status);
        // 让下面的按钮跟随全选按钮的状态
        this.oneSel(status)
    }
    // 跟随全选
    oneSel(status) {
        // 获取单选按钮
        let checkbox = this.$('.good-checkbox')
        // console.log(checkbox);
        // 循环让单选按钮跟随全选按钮状态
        checkbox.forEach(ele => {
            // console.log(ele);
            ele.checked = status
        })
        this.mount()
        if (!status) this.$('.summoney span').innerHTML = "0.00"
    }
    // 单选按钮状态
    oneSta(tar) {
        // 如果一个为false 全选按钮就为false
        if (!tar.checked) this.$('.cart-th input').checked = false;
        // 获取单选按钮
        let btn = document.querySelectorAll('.good-checkbox')
        // console.log(btn);
        // 转换为真数组
        let btn1 = Array.from(btn);
        // console.log(btn1);
        // 使用some函数
        let res = btn1.some((ele) => {
            // console.log(ele);
            return !ele.checked
        })
        // console.log(res);
        if (!res) this.$('.cart-th input').checked = true;
    }


    // 使用递归获取父级节点
    parent(ele, target = 'UL') {
        if (ele.nodeName == target) {
            return ele
        }
        return this.parent(ele.parentNode)
    }
    // 获取父节点下的子节点  
    boy(fat, boy, attr = 'value') {
        return fat.querySelector(boy)[attr];
    }





    // 判断登录状态 设置用户名
    loginStatus() {
        let status = localStorage.getItem('id')
        let username = localStorage.getItem('uname')
        // console.log(this.$('.fr li a')[0]);
        if (status) {
            this.$('.f10').forEach(ele => {
                this.$('.fr li a')[0].innerHTML = username
            })
        }
    }
    // 封装获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}
new Cart